<template>

  <div class="details" v-loading="loading">

    <div class="item" :class="{'open': baseTableOpen}" @click="baseTableOpen = true">
      <div class="item-hd clearfix">
        <div class="left clearfix">
          <h3 class="title info">系统-下发贬损者信息</h3>
        </div>
        <div class="right">
          <span class="date">{{dateFormat(baseInfo.createTime)}}</span>
          <i class="el-icon-minus" v-show="baseTableOpen" @click.stop="baseTableOpen = false"></i>
        </div>
      </div>
      <el-collapse-transition>
        <div class="item-bd" v-show="baseTableOpen">
          <details-table :details="details"></details-table>
        </div>
      </el-collapse-transition>
    </div>

    <div class="flows">
      <div class="item"
           v-for="(item,index) in flows"
           :class="{'open': flowsPanelOpenStatus[index]}"
           @click="openFlowPanel(index)">
        <div class="item-hd clearfix">
          <div class="left clearfix">
            <h3 class="title info">{{item.handler}}</h3>
            <span class="info">操作：{{item.operation}}</span>
          </div>
          <div class="right">
            <span class="date">{{dateFormat(item.createTime)}}</span>
            <i class="el-icon-minus" v-show="flowsPanelOpenStatus[index]" @click.stop="closeFlowPanel(index)"></i>
          </div>
        </div>
        <el-collapse-transition>
          <div class="item-bd" v-show="flowsPanelOpenStatus[index]">
            <details-form :data="item" :disabled="true"></details-form>
          </div>
        </el-collapse-transition>
      </div>
    </div>

    <div class="item open bgwhite" v-if="showUserOpnForm">
      <div class="item-hd clearfix">
        <div class="left clearfix">
          <h3 class="title info">{{baseInfo[currentHandlerField]}}</h3>
        </div>
      </div>
      <el-collapse-transition>
        <div class="item-bd">
          <details-form
            ref="form"
            :validateFields="detailsFormValidate"
            :isFromMessage="isFromMessage"
            @derogatory-categories-change="handleDisabledBtnsChange">
          </details-form>
        </div>
      </el-collapse-transition>
    </div>

    <btns class="btnsbar"
          :disabledBtns="disabledBtns"
          :details="details"
          @sleep="handleSleep"
          @reject="handleReject"
          @cancel="handleCancel"
          @next="handleNext"
          @done="handleDone"
          @adopted="handleAdopted"
          @submit="handleSubmit"
          @ordersRelate="ordersRelate">
    </btns>

  </div>

</template>

<script>
  import {mapState, mapGetters, mapActions} from 'vuex'
  import CollapseTransition from 'element-ui/lib/transitions/collapse-transition'
  import DetailsTable from './detailsTable'
  import Btns from './btns'
  import DetailsForm from './detailsForm'
  import {
    getDepartment,
    getOrderDetails,
    userOpnCenterNext,
    userOpnCenterTrans,
    userOpnCenterVisit,
    saleHQNext,
    saleHQTrans,
    saleHQVisit,
    subAdminNext,
    subAdminHandle
  } from '@/service/getData'

  export default {
    components: {
      ElCollapseTransition: CollapseTransition,
      DetailsTable,
      Btns,
      DetailsForm
    },
    data() {
      return {
        loading: false,
        baseTableOpen: true,
        flowsPanelOpenStatus: [],
        details: {
          characterId: '',
          ctype: 0,
          orderid: '',
          npsBaseInfo: {},
          twCallbackBaseInfo: {},
          npsDerogatoryInfo: {},
          npsApproveFlows: []
        },
        flows: [],
        opnCode: '',
        disabledBtns: [],
        isTwDtails: false,  // 当前处于关联单据下的二次回访详情
        detailsFormValidate: {
          branchCompany: true
        }
      }
    },
    computed: {
      ...mapState({
        platformType: state => state.disparageManage.platformType,
        ctype: state => state.disparageManage.ctype,
        currentOrderCtype: state => state.disparageManage.currentOrderCtype,
        currentOrderStatus: state => state.disparageManage.currentOrderStatus,
        currentOrderDetails: state => state.disparageManage.currentOrderDetails
      }),
      ...mapGetters([
        'userType',
        'disparageType'
      ]),

      // 订单characterId
      orderCharacterId() {
        return this.checkUserType(this.details.characterId)
      },

      // 是否分公司管理员
      isFGLY() {
        return this.orderCharacterId === this.platformType.FGLY
      },

      // 是否销司总部
      isXSZB() {
        return this.orderCharacterId === this.platformType.XSZB
      },

      // 是否用户运营中心
      isYYZX() {
        return this.orderCharacterId === this.platformType.YYZX
      },

      // 基础信息
      baseInfo() {
        return this.details[this.details.ctype === 2 ? 'twCallbackBaseInfo' : 'npsBaseInfo'] || {}
      },

      // 贬损信息
      deroInfo() {
        return this.details.npsDerogatoryInfo || {}
      },

      // 订单状态
      orderStatus() {
        const fields = ['derogatoryIssueStatus', 'derogatoryTransStatus', 'twCallbackStatus', 'brManagerStatus']
        let index
        if(this.isFGLY) {
          index = this.currentOrderCtype == 2 ? 2 : 3
        }else{
          index =  this.deroInfo.ctype
        }
        const fieldName = fields[index]
        return this.deroInfo[fieldName]
      },

      // 是否显示用户操作表单
      showUserOpnForm() {
        const status = this.orderStatus
        const ctype = this.deroInfo.ctype
        const BSXF = this.ctype.BSXF
        const BSZH = this.ctype.BSZH
        const ECHF = this.ctype.ECHF
        if(this.isYYZX) {
          if(ctype === BSXF || ctype === BSZH) {
            return status === '1'
          }
          const items = ['1', '6', '7', '14']
          return items.indexOf(status) > -1
        }
        if(this.isXSZB) {
          if(ctype === BSXF || ctype === BSZH) {
            return status === '1'
          }
          const items = ['1', '6', '7']
          return items.indexOf(status) > -1
        }
        const items = ['1', '2', '11', '13']
        return items.indexOf(status) > -1
      },

      // 当前处理人fieldName
      currentHandlerField() {
        const handlerField = [
          'derogatoryIssueCurHandler',
          'derogatoryTransCurHandler',
          'twCallbackCurHandler',
          'brManagerCurHandler'
        ]
        return handlerField[this.deroInfo.ctype]
      },

      // 来源message
      isFromMessage() {
        const baseInfo = this.currentOrderDetails.npsBaseInfo || {}
        return baseInfo.npsFlag === 'message'
      }
    },
    created() {
      this.getOrderDetails({
        characterId: this.userType,
        ctype: this.$route.query.ctype,
        orderid: this.$route.params.orderid,
        associationTypes: 0
      })
    },
    beforeDestroy() {
      this.$store.commit('SET_CURRENTORDERDETAILS', {})
    },
    methods: {

      // 检测用户类型characterId
      checkUserType(characterId) {
        const regs = [/^_a_g_umc/, /^_a_g_xs/, /^_a_g_d_/]
        const index = regs.findIndex(item => item.test(characterId))
        return index > -1 ? regs[index].toString().replace(/[/^]/g, '') : ''
      },

      // 获取订单详情并筛选对应的流，如果需要则设置子组件默认值
      async getOrderDetails(data) {
        const res = await getOrderDetails(this.jsonToQueryStr(data))
        const details = res.data.data
        const allFlows = details.npsApproveFlows || []
        this.details = details

        this.flows = (this.isFGLY ? allFlows : allFlows.filter(item => {
          if(details.ctype == 1) {
            return item.ctype == 1 || item.ctype == 3
          }
          return item.ctype === details.ctype
        })).reverse()

        // this.flows = allFlows ? allFlows.filter(item => {
        //   if(details.ctype == 1) {
        //     return item.ctype == 1 || item.ctype == 3
        //   }
        //   return item.ctype === details.ctype
        // }).reverse() : []

        this.isTwDtails = details.ctype === 2
        this.showUserOpnForm && this.$nextTick(() => {
          const form = this.$refs.form
          form.autoFillBranchCompany(this.baseInfo.branchCompany)
          const hasRealPersonCharge = this.deroInfo.personCharge && this.deroInfo.personChargeId
          const isOpnNext = ['1', '13'].indexOf(this.orderStatus) > -1
          if (this.isFGLY && isOpnNext && hasRealPersonCharge) {
            form.setPersonCharge(this.deroInfo.personChargeId, this.deroInfo.personCharge)
          }
        })
        this.$store.commit('SET_CURRENTORDERUSERTYPE', this.details.characterId)
        this.$store.commit('SET_CURRENTORDERCTYPE', this.details.ctype)
        this.$store.commit('SET_CURRENTORDERSTATUS', this.orderStatus)
        this.$store.commit('SET_CURRENTORDERDETAILS', this.details)
      },

      // 设置禁用按钮
      handleDisabledBtnsChange(value) {
        const items = ['0', '5', '6']
        const flag = items.indexOf(value) > -1
        this.disabledBtns = flag ? ['休眠', '下发'] : []
      },

      // 打开审批流面板
      openFlowPanel(index) {
        this.$set(this.flowsPanelOpenStatus, index, true)
      },

      // 关闭审批流面板
      closeFlowPanel(index) {
        this.$set(this.flowsPanelOpenStatus, index, false)
      },

      // 获取请求参数
      getPostData() {

        const status = this.orderStatus
        const ctype = this.deroInfo.ctype
        const BSXF = this.ctype.BSXF
        const BSZH = this.ctype.BSZH
        const ECHF = this.ctype.ECHF

        const detilsForm = this.$refs.form
        const form = detilsForm.form
        const upload = detilsForm.uploadResponse
        const info = this.details.npsDerogatoryInfo

        // 必要公共参数
        let params = {
          orderid: info.orderid,
          characterId: info.characterId,
          ctype: info.ctype,
          processId: info.processId,
          taskId: info.taskId,
          result: this.opnCode,
          suggestion: form.suggestion
        }

        if(this.isYYZX) {
          if(ctype === BSXF) {
            const baseInfo = this.currentOrderDetails.npsBaseInfo || {}
            const reason = this.isFromMessage ? baseInfo.salesSectionRecommendationLevelComment : form.derogatoryReason
            params.derogatoryCategories = form.derogatoryCategories
            params.derogatoryReason = reason
          }
        }else if(this.isXSZB) {
          if((ctype === BSXF || ctype === ECHF) && status === '1') {
            params.toGroupId = form.branchCompanyId
          }
        }else{
          if(status === '1' || status === '13') {
            params.personChargeId = form.personChargeId
          }else if(status === '2' || status === '11'){
            const index = form.followResult
            const fields1 = ['cptCommuContent', 'appealContent', 'hpCommuContent']
            const fields2 = ['cptFollowWay', '', 'hpFollowWay']
            const contentField = fields1[index]
            const followWayField = fields2[index]
            params[contentField] = form[contentField]
            params.list = upload
            if (index !== 1) {
              params[followWayField] = form[followWayField]
            }
            if (index === 2) {
              params.seekHelpReason = form.seekHelpReason
            }
            delete params.suggestion
          }
        }
        return params
      },

      // 把对象转成查询字符串
      jsonToQueryStr(data) {
        let result = []
        for (let key in data) {
          data.hasOwnProperty(key) && result.push(`${key}=${data[key]}`)
        }
        return result.join('&')
      },

      // 提交审批，先进行表单校验
      post(validateSuggestion) {
        this.$refs.form.validate().then(() => {
          const ctype = this.deroInfo.ctype
          const status = this.orderStatus
          const fns1 = [userOpnCenterNext, userOpnCenterTrans, userOpnCenterVisit]
          const fns2 = [saleHQNext, saleHQTrans, saleHQVisit]
          const data = this.getPostData()
          let params = data
          if (validateSuggestion && !data.suggestion) {
            this.$message.closeAll()
            this.$message.warning('请填写意见！')
            return false
          }

          let request
          if (this.isYYZX) {
            request = fns1[ctype]
          } else if (this.isXSZB) {
            request = fns2[ctype]
          } else if (this.isFGLY) {
            if(status == 1 || status == 13) {
              request = subAdminNext
            }else if(status == 2 || status == 11) {
              request = subAdminHandle
            }
          }
          this.loading = true
          request(params).then(res => {
            this.$message({
              duration: 1000,
              message: res.data.code === 1 ? '操作成功！' : '操作失败！',
              type: res.data.code === 1 ? 'success' : 'error',
              onClose: () => {
                this.backToListView()
              }
            })
          }).catch(() => {}).finally((err) => {
            this.loading = false
            this.detailsFormValidate.branchCompany = true
          })

        }).catch(() => {
          console.log('post form validate catch')
          this.$message.closeAll()
          this.$message.warning('请填写表单必填字段！')
          return false
        })

      },

      // 休眠
      handleSleep() {
        this.opnCode = 2
        this.post(1)
      },

      // 驳回
      handleReject() {
        this.detailsFormValidate.branchCompany = false
        this.opnCode = this.isYYZX && this.deroInfo.ctype === this.ctype.BSXF ? 7 : 0
        this.$nextTick(() => {
          this.post(1)
        })
      },

      // 下发
      handleNext() {
        this.opnCode = this.isFGLY && (this.orderStatus == 1 || this.orderStatus == 13) ? 5 : 1
        this.post(this.isYYZX && this.deroInfo.ctype === this.ctype.ECHF)
      },

      // 取消
      handleCancel() {
        this.backToListView()
      },

      // 通过
      handleAdopted() {
        this.opnCode = 1
        this.post()
      },

      // 提交
      handleSubmit() {
        const followResult = this.$refs.form.form.followResult
        const opnCodes = [4, 3, 6]
        this.opnCode = opnCodes[followResult]
        this.post()
      },

      // 完成
      handleDone() {
        this.opnCode = 8
        this.post()
      },

      // 回到列表页
      backToListView() {
        this.$router.push({
          name: 'DisparageList'
        })
      },

      // 关联单据
      ordersRelate(ctype) {
        this.getOrderDetails({
          characterId: this.userType,
          ctype: ctype,
          orderid: this.details.orderid,
          associationTypes: this.isTwDtails ? 1 : ctype == 2 ? 2 : 0
        })
      },
      // 时间格式化
      dateFormat(date) {
        if (!Date.parse(date)) {
          return ''
        }
        var t = new Date(date),
          yyyy = t.getFullYear(),
          MM = t.getMonth() + 1,
          dd = t.getDate(),
          h = t.getHours(),
          m = t.getMinutes(),
          s = t.getSeconds(),
          today = new Date().getDate()
        if (dd === today) {
          if (h < 6) {
            h = '凌晨 ' + h
          } else if (h < 8) {
            h = '早晨 ' + h
          } else if (h < 12) {
            h = '上午 ' + h
          } else if (h < 14) {
            h = '中午 ' + (h - 12)
          } else if (h < 18) {
            h = '下午 ' + (h - 12)
          } else if (h < 20) {
            h = '傍晚 ' + (h - 12)
          } else {
            h = '晚上 ' + (h - 12)
          }
        } else {
          h = h < 10 ? '0' + h : h
        }
        MM = MM < 10 ? '0' + MM : MM
        dd = dd < 10 ? '0' + dd : dd
        m = m < 10 ? '0' + m : m
        s = s < 10 ? '0' + s : s
        return [yyyy, MM, dd].join('-') + ' ' + [h, m, s].join(':')
      }

    }
  }
</script>

<style lang="scss" scoped>

  .clearfix:after {
    content: '';
    display: block;
    height: 0;
    visibility: hidden;
    clear: both;
  }

  .details {
    position: relative;
  }

  .item {
    box-sizing: border-box;
    margin-bottom: 20px;
    padding: 20px;
    border: 2px solid #eee;
    background-color: #f8f8f8;
    cursor: pointer;
    &.open {
      cursor: default;
    }
    &.bgwhite {
      background-color: #fff;
    }
  }

  .item-hd {
    line-height: 30px;
    .left {
      float: left;
      .info {
        float: left;
        margin-right: 50px;
      }
    }
    .right {
      float: right;
      i {
        position: relative;
        top: 3px;
        display: inline-block;
        padding: 0;
        border: 1px solid #eee;
        margin-left: 10px;
        font-size: 16px;
        font-weight: bold;
        color: rgba(red, .75);
        cursor: pointer;
        &:hover {
          color: red;
        }
      }
    }

  }

  .item-bd {
    padding-top: 20px;
  }

  .flows {
    margin-top: 20px;
  }

  .btnsbar {
    position: absolute;
    top: -28px;
    right: 0;
  }


</style>
